<template>
    <div class="app-container">
        <el-row>
            <el-col :span="24">
                <el-card shadow="always" header="无线超频统计情况" style="margin-bottom: 20px;">
                    <el-table :data="statisticsTableData" v-loading="contLoading" max-height="500px">
                        <el-table-column prop="county" label="区县" />
                        <el-table-column prop="countOverFrequencyFour" label="超3量" />
                        <el-table-column prop="countOverFrequencyFive" label="超4量" />
                        <el-table-column prop="countOverFrequencySix" label="超5量" />
                    </el-table>
                </el-card>
            </el-col>
            <el-col :span="24">
                <el-card shadow="always" header="无线超频列表">
                    <el-form :model="queryParams" :inline="true" label-width="120px">
                        <el-form-item label="所属区县：" prop="county">
                            <el-select v-model="queryParams.county" placeholder="请选择所属区县" clearable
                                style="width: 240px">
                                <el-option v-for="dict in nhp_county_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="小区名称" prop="neName">
                            <el-input v-model="queryParams.neName" placeholder="请输入小区名称" clearable
                                style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="告警主题" prop="alarmTopic">
                            <el-input v-model="queryParams.alarmTopic" placeholder="请输入告警主题" clearable
                                style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="工单频次(>=)" prop="countSameStationAlarm">
                            <el-input type="number" v-model="queryParams.countSameStationAlarm" placeholder="请输入工单频次"
                                clearable style="width: 240px" />
                        </el-form-item>
                        <el-form-item label="工单生成时间" prop="createTime">
                            <el-date-picker v-model="queryParams.createStartEnd" type="daterange"
                                start-placeholder="开始时间" end-placeholder="结束时间" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="searchData">查询</el-button>
                            <el-button @click="unsetQueryForm"><el-icon>
                                    <RefreshRight />
                                </el-icon>重置</el-button>
                        </el-form-item>
                    </el-form>
                    <el-row style="margin-bottom: 10px;">
                        <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
                    </el-row>
                    <!-- @sort-change="sortChange" -->
                    <el-table :data="exitTableData" @sort-change="sortChange" style="width: 100%"
                        v-loading="listLoading">
                        <el-table-column fixed prop="county" label="区县" width="70" align="center" />
                        <el-table-column prop="neName" label="小区名称" min-width="250" align="center"
                            show-overflow-tooltip />
                        <el-table-column prop="alarmTopic" label="告警主题" width="auto" min-width="125" align="center" />
                        <el-table-column prop="lastHandleTime" width="110" label="最后处理时间(>=4要填)" sortable="custom" />
                        <el-table-column prop="overFrequencyCause" width="auto" min-width="150" label="超频原因与处理进度(>=5要填)"
                            sortable="custom" />
                        <el-table-column prop="countSameStationAlarm" label="工单频次" width="60" align="center" />
                        <el-table-column prop="orderCreateTime" label="工单生成时间" :formatter="dateFormatter" width="100"
                            align="center" sortable="custom" />
                        <el-table-column prop="faultEliminateTime" label="故障消除时间" :formatter="dateFormatter" width="100"
                            align="center" />
                        <el-table-column fixed="right" label="操作" min-width="228" align="center">
                            <template #default="scope">
                                <el-button link type="primary" size="small"
                                    @click="setRemark(scope.row, 'clsj')">最后处理时间<br />(>=4要填)</el-button>
                                <el-button link type="primary" size="small"
                                    @click="setRemark(scope.row, 'cpyy')">超频原因与处理进度<br />(>=5要填)</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
                        @pagination="listWirelessOverclockingData" :autoScroll="false" />
                </el-card>
            </el-col>
        </el-row>

        <export-dialog ref="refExportDialog" @directExport="directExportData" />
        <SetRemark ref="refSetRemark" @reflash="listWirelessOverclockingData" />

    </div>
</template>

<script setup>
import { getToken } from '@/utils/auth'
import { queryWirelessOverclockingList, queryWirelessOverclockingCounty } from '@/api/biz/maintenance';
import { useConfigStore } from '@/store/modules/config.js'
import SetRemark from './components/SetRemark.vue'

const { proxy } = getCurrentInstance();
const { nhp_county_type } = proxy.useDict("nhp_county_type");

const queryParams = ref({
})
const importDialogVisible = ref(false)
const exitTableData = ref([])
const networkTypeOptions = [
    {
        key: "4G",
        value: "103"
    },
    {
        key: "5G",
        value: "108"
    },
    {
        key: "2G",
        value: "101"
    }
]
const currentPage = ref(1)
const refExportDialog = ref(null)
const refSetRemark = ref(null)
const pageSize = ref(10)
const total = ref(0)
const nowSortContent = ref();
const nowOrder = ref();
const configStoreData = useConfigStore()
let securityFlagConfig = configStoreData.configList.filter(item => item.configKey === 'sys.securityFlag')[0]

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/maintenance/exitImport"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });

const statisticsTableData = ref([])

let contLoading = ref(false)
let listLoading = ref(false);

const searchData = () => {
    listWirelessOverclockingData()
    getWirelessOverclockingCounty()
}

const setRemark = (row, type) => {
    row.start = queryParams.value.createStartEnd[0]
    row.end = queryParams.value.createStartEnd[1]
    refSetRemark.value.show(row, type)
}

const getDateRange = () => {
    const startDay = 20
    let tempDateRange = []
    let currentDate = new Date();
    let year = currentDate.getFullYear();
    let month = currentDate.getMonth() + 1
    let day = currentDate.getDate()
    // let dayRes = day <= startDay ? day + 1 : startDay
    let dayRes = day + 1

    /**
     * 上个月21日 - 当前月份20
     * 如果当前日期<=20  
     * <=20 上月20 ~ 当天+1
     * >20 当月20 ~ 当天+1
     * 
     */
    // >20 当月20 ~ 当天+1
    if (day > startDay) {
        tempDateRange = [`${year}-${month}-${startDay}`, `${year}-${month}-${dayRes}`]
    } else {
        // 如果当前月份 = 1, 且月份< 20, 则取去年12月20 ~ 当前日期+1
        if (month == 1) {
            tempDateRange = [`${year - 1}-12-${startDay}`, `${year}-${month}-${dayRes}`]
        } else {
            // <=20 上月20 ~ 当天+1
            tempDateRange = [`${year}-${month - 1}-${startDay}`, `${year}-${month}-${dayRes}`]
        }
    }
    queryParams.value.createStartEnd = [new Date(tempDateRange[0]), new Date(tempDateRange[1])]
}

const getWirelessOverclockingCounty = () => {
    let param = {}
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.start = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.end = queryParams.value.createStartEnd[1].toLocaleDateString()
    }

    contLoading.value = true
    queryWirelessOverclockingCounty(param).then(res => {
        statisticsTableData.value = res.rows
        contLoading.value = false

        if (statisticsTableData.value[statisticsTableData.value.length - 1]?.county == null) {
            delete statisticsTableData.value[statisticsTableData.value.length - 1]
        }
    })
}

function sortChange(column, prop, order) {
    nowOrder.value = column.order;
    nowSortContent.value = column.prop;
    listWirelessOverclockingData();
}

const unsetQueryForm = () => {
    queryParams.value = {}
    getDateRange()
    searchData()
}

function importFile() {
    importDialogVisible.value = true
}

const getParams = () => {
    let param = {
        pageSize: pageSize.value,
        pageNum: currentPage.value,
        ...queryParams.value,
        order: nowOrder.value,
        sortContent: nowSortContent.value,
    }

    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.start = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.end = queryParams.value.createStartEnd[1].toLocaleDateString()

        delete param.createStartEnd
    }

    return param
}

function listWirelessOverclockingData() {
    listLoading.value = true
    queryWirelessOverclockingList(getParams()).then(res => {
        listLoading.value = false
        total.value = res.total
        exitTableData.value = res.rows
    })
}

function networkTypeFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    if (cellValue == '103') {
        return '4G';
    } else if (cellValue == '108') {
        return '5G';
    } else if (cellValue == '101') {
        return '2G';
    }
}

function dateFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    return formattedDateTimeString;
}

/* function endureFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    var originalDate = new Date(cellValue);
    //计算originalDate距离当前的时间的小时数
    // 获取当前时间
    var currentDate = new Date();
    // 计算时间差（毫秒）
    var timeDifference = currentDate - originalDate;
    // 将毫秒转换为小时（1小时 = 3600000毫秒）
    // 保留两位小数
    var hoursDifference = timeDifference / (1000 * 3600);
    hoursDifference = hoursDifference.toFixed(2);
    return hoursDifference;
} */

// 导出明面上的数据
function exportData() {
    //首先判断金库模式开关是否开启
    if (securityFlagConfig.configValue == "true") {
        // refExportDialog.value.show(param)
    } else {
        //未开启
        proxy.download("/maintenance/exportWirelessOverclockingList", {
            ...getParams()
        }, `无线超频管理_${new Date().getTime()}.xlsx`);
    }
}

function directExportData() {
    let param = {
        pageSize: pageSize.value,
        pageNum: currentPage.value,
        ...queryParams.value
    }

    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
        delete param.createStartEnd
    }

    proxy.download("/maintenance/exportWirelessOverclockingList", {
        ...getParams()
    }, `无线超频管理_${new Date().getTime()}.xlsx`);
}

getDateRange()
searchData()
</script>